<template>
  <div class="app-container">
    <div style="margin-bottom: 20px;" class="clearfix">
      <el-button v-show="checkPermission('courseClassifyAdd')" v-waves class="filter-item" type="primary" icon="el-icon-plus" style="float:right" @click="handleAdd">
        添加
      </el-button>
    </div>

    <el-table
      :key="tableKey"
      v-loading="listLoading"
      :data="list"
      border
      fit
      highlight-current-row
      style="width: 100%;"
      :element-loading-text="g.loadingStr"
      :header-cell-style="{background:g.mainColor}"
    >
      <el-table-column label="序号" align="center" width="100" fixed>
        <template slot-scope="{$index}">
          <span>{{ $index + 1 + ( listQuery.currentPage - 1 ) * listQuery.pageSize }}</span>
        </template>
      </el-table-column>
      <el-table-column label="图标" align="center" width="200">
        <template slot-scope="{row}">
          <span><img :src="row.categoryIcon" alt="" class="table-row-img"></span>
        </template>
      </el-table-column>
      <el-table-column label="名称" align="center" width="220">
        <template slot-scope="{row}">
          <span>{{ row.categoryName }}</span>
        </template>
      </el-table-column>
      <el-table-column label="子分类" align="center">
        <template slot-scope="{row,$index}">
          <el-tag
            v-for="tag in row.categoryVO"
            :key="tag.categoryName"
            style="margin: 5px;"
            closable
            :type="colors[row.categoryVO.indexOf(tag) % colors.length]"
            @close="handleItemClose(tag,$index)"
            @click="handleItemClick(tag,$index)"
          >
            {{ tag.categoryName }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="状态" align="center" width="90px">
        <template slot-scope="{row}">
          <span>{{ row.flagEnable === 1 ? '启用' : '禁用' }}</span>
        </template>
      </el-table-column>
      <el-table-column fixed="right" label="操作" align="center" width="300px">
        <template slot-scope="{row,$index}">
          <el-button type="primary" size="mini" @click="handleChildrenClassifyAdd(row)">
            添加子分类
          </el-button>
          <el-button v-show="checkPermission('courseClassifyEdit')" type="primary" size="mini" @click="handleUpdate(row)">
            编辑
          </el-button>
          <el-button type="danger" size="mini" @click="handleDel(row,$index)">
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total>0" :total="total" :page.sync="listQuery.currentPage" :limit.sync="listQuery.pageSize" @pagination="getList" />

    <el-dialog
      title="修改子分类"
      :visible.sync="dialogChildrenClassifyVisible"
      width="30%"
    >

      <el-form ref="form" label-width="140px">
        <el-form-item label="名称">
          <el-input v-model="childrenClassifyData.name" clearable placeholder="请输入名称" />
        </el-form-item>
        <el-form-item label="图片">
          <el-upload
            action="#"
            list-type="picture-card"
            :on-preview="handlePictureCardPreview"
            :on-remove="handleRemove"
            :on-change="handleChange"
            :auto-upload="false"
            :class="{hide:hideUpload}"
            :file-list="imgsList"
          >
            <i class="el-icon-plus" />
          </el-upload>
          <el-dialog :visible.sync="dialogVisible">
            <img width="100%" :src="dialogImageUrl" alt="">
          </el-dialog>
        </el-form-item>
        <el-form-item label="是否启用">
          <el-switch v-model="childrenClassifyData.flagEnable" />
        </el-form-item>
      </el-form>

      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogChildrenClassifyVisible = false">取 消</el-button>
        <el-button type="primary" @click="handleItemUpdateSubmit">确 定</el-button>
      </span>
    </el-dialog>

  </div>
</template>

<script>

import waves from '@/directive/waves' // waves directive
import Pagination from '@/components/Pagination' // secondary package based on el-pagination
import { courseClassifyList, courseClassifyDel, courseClassifyDetail, courseClassifyUpdate, courseClassifyAdd } from '@/api/course'

export default {
  name: 'CourseClassifyList',
  directives: { waves },
  components: { Pagination },
  data() {
    return {
      colors: [
        '',
        'success',
        'info',
        'warning',
        'danger'
      ],

      tableKey: 0,
      list: null,
      total: 0,
      listLoading: true,
      listQuery: {
        currentPage: 1,
        pageSize: 10
      },
      childrenClassifyData: {},

      imgsList: [],
      hideUpload: false,
      imgFile: null,

      dialogImageUrl: '',
      dialogVisible: false,

      dialogChildrenClassifyVisible: false,
      dialogChildrenClassifyType: '',
      currentListRow: {}
    }
  },
  created() {
  },
  mounted() {
    this.getList()
  },
  methods: {
    getList() {
      this.listLoading = true
      courseClassifyList(this.listQuery).then(response => {
        console.log(response.data)
        this.list = response.data.records
        this.total = response.data.total
        this.listLoading = false
      })
    },
    submit() {
      this.listQuery.currentPage = 1
      this.getList()
    },
    handleUpdate(row) {
      console.log(row)
      this.$router.push({ name: 'CourseClassifyEdit', params: { id: row.categoryId }})
    },
    handleDel(row, index) {
      console.log(row)

      this.$confirm('是否确认删除该分类？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        courseClassifyDel({
          id: row['categoryId']
        }).then(response => {
          this.$message({ message: '操作成功', type: 'success' })
          this.list.splice(index, 1)
        })
      })
    },
    handleAdd() {
      this.$router.push('CourseClassifyAdd')
    },
    handleChildrenClassifyAdd(row) {
      console.log(row)
      this.dialogChildrenClassifyType = 'add'

      this.currentListRow = row
      this.childrenClassifyData = {}
      this.imgsList = []
      this.hideUpload = false
      this.dialogChildrenClassifyVisible = true
    },
    handleItemClose(tag, index) {
      console.log(JSON.stringify(tag) + '----' + index)

      this.$confirm('是否确认删除该子分类？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        courseClassifyDel({
          id: tag['categoryId']
        }).then(response => {
          this.$message({ message: '操作成功', type: 'success' })
          this.list[index].categoryVO.splice(this.list[index].categoryVO.indexOf(tag), 1)
        })
      })
    },
    handleItemClick(tag, index) {
      console.log(JSON.stringify(tag) + '----' + index)

      this.dialogChildrenClassifyType = 'edit'

      courseClassifyDetail({ id: tag['categoryId'] }).then(response => {
        this.childrenClassifyData = response.data
        this.childrenClassifyData.flagEnable = this.childrenClassifyData.flagEnable === 1
        if (response.data.iconUrl !== null && response.data.iconUrl !== '') {
          this.imgsList = [
            { url: response.data.iconUrl }
          ]
          this.hideUpload = true
        }
        this.dialogChildrenClassifyVisible = true
      })
    },
    handleItemUpdateSubmit() {
      if (this.childrenClassifyData.name.trim() === '') {
        this.$message({ message: '请输入名称', type: 'error' })
        return
      }

      if (this.imgFile === null && this.childrenClassifyData.iconUrl === null) {
        this.$message({ message: '请选择图片', type: 'error' })
        return
      }

      if (this.imgFile !== null) {
        this.uploadImgToOss(this.imgFile).then(response => {
          console.log('图片上传结果：' + JSON.stringify(response))
          this.imgUrl = response
          if (this.dialogChildrenClassifyType === 'edit') {
            this.handleItemUpdateGoToSubmit()
          } else {
            this.handleItemAddGoToSubmit()
          }
        })
      } else {
        if (this.dialogChildrenClassifyType === 'edit') {
          this.handleItemUpdateGoToSubmit()
        } else {
          this.handleItemAddGoToSubmit()
        }
      }
    },
    handleItemAddGoToSubmit() {
      courseClassifyAdd(
        {
          parentId: this.currentListRow['categoryId'],
          name: this.childrenClassifyData.name,
          flagEnable: this.childrenClassifyData.flagEnable ? 1 : 0,
          iconUrl: this.imgUrl,
          classify: this.currentListRow['classify'],
          type: 1
        }).then(response => {
        this.dialogChildrenClassifyVisible = false
        this.$message({ message: '操作成功', type: 'success' })
        this.getList()
      })
    },
    handleItemUpdateGoToSubmit() {
      courseClassifyUpdate(
        {
          id: this.childrenClassifyData['id'],
          name: this.childrenClassifyData.name,
          flagEnable: this.childrenClassifyData.flagEnable ? 1 : 0,
          iconUrl: this.imgUrl
        }).then(response => {
        this.dialogChildrenClassifyVisible = false
        this.$message({ message: '操作成功', type: 'success' })
        this.getList()
      })
    },
    handleRemove(file, fileList) {
      console.log('handleChange')
      console.log(file)
      this.hideUpload = false
    },
    handlePictureCardPreview(file) {
      this.dialogImageUrl = file.url
      this.dialogVisible = true
    },
    handleChange(file, fileList) {
      console.log('handleChange' + fileList.length)
      console.log(file)
      this.imgFile = fileList.length > 0 ? file : null
      this.hideUpload = fileList.length >= 1
    }

  }
}
</script>

<style lang="scss" scoped>
.hide /deep/.el-upload--picture-card {
	display: none;
}
</style>
